<!DOCTYPE html>
<html lang = "en">
<head>
    <meta charset = "UTF-8">
    <title>Title</title>

    <!--=====================================================================-->
    <script>
        //

        window.onload = function () {

            let oDiv = document.getElementById('div1');
            oDiv.style.left = 0 + 'px';
            oDiv.style.top = 0 + 'px';

            let speed = 50;

            //备注,有些非asdf的按键例如F1,esc等,在onkeydown是可以弹出,但在onkeypress下不可以
            document.onkeydown = function (ev) {
                if (ev.key === 'ArrowLeft') {
                    oDiv.style.left = oDiv.offsetLeft - speed + 'px';
                }

                if (ev.key === 'ArrowDown') {
                    oDiv.style.top = oDiv.offsetTop + speed + 'px';
                }

                if (ev.key === 'ArrowUp') {
                    oDiv.style.top = oDiv.offsetTop - speed + 'px';
                }

                if (ev.key === 'ArrowRight') {
                    oDiv.style.left = oDiv.offsetLeft + speed + 'px';
                }

            };
        };
        //存在问题:按住后会有卡顿感
        //可以通过设定一个定时器,按下后让上下左右对应的bool变为true继而使div移动,但在切换方向时依然有卡顿感





    </script>
</head>

<body>

<div>
    <div style="height: 50px;width: 50px;background: pink;position: absolute; left: 0px;top: 0px;" id="div1"></div>

</div>

</body>
</html>